from app.log_config import monitor_logger
from app.udp_server import heartbeatMap
from app.crud_operate_log import operate_log_service
from app.crud_config import config_service
from datetime import datetime

def heart_check():
    monitor_logger.info("heartbeat check")
    current_time = datetime.now()
    for key, value in heartbeatMap.items():
        monitor_logger.info("key:{}, value:{}".format(key, value))
        dev_heart_time = datetime.strptime(str(value), "%Y-%m-%d %H:%M:%S")
        # 计算时间差
        time_difference = current_time - dev_heart_time
        delay_seconds = time_difference.total_seconds()
        # monitor_logger.info("delay_seconds:{}".format(delay_seconds))
        dev = key.split("_")[0]
        if delay_seconds > 150:
            monitor_logger.info(f"device {dev} is offline")
            heartbeat_fail_reboot_flag = config_service.selectByKey("heartbeat_fail_reboot_flag")[1]
            if heartbeat_fail_reboot_flag == '0':
                operate_log_service.insert(f"{dev}设备离线", "monitor", current_time)
                config_service.updateByKey("heartbeat_fail_reboot_flag", '1')
            else:
                monitor_logger.info(f"device {dev} keep offline. upload alarm msg")


